package transferstats

import (
	"errors"
	"net/http"
	"time"

	"github.com/chihaya/chihaya/middleware"
	"gopkg.in/yaml.v2"
)

const Name = "transfer_stats"

var ErrInvalidPTSiteEndpoint = errors.New("invalid ptsite endpoint")

type Config struct {
	PTSiteEndpoint string        `yaml:"ptsite_endpoint"`
	Timeout        time.Duration `yaml:"timeout"`
	Debug          bool          `yaml:"debug"`
	Interval       time.Duration `yaml:"interval"`
}

const (
	defaultTimeout  = 10 * time.Second
	defaultInterval = 5 * time.Minute
)

func (c Config) LogFields() []interface{} {
	return []interface{}{
		"ptsite_endpoint", c.PTSiteEndpoint,
		"timeout", c.Timeout,
		"debug", c.Debug,
		"interval", c.Interval,
	}
}

func (c *Config) NewHook() (middleware.Hook, error) {
	if c.PTSiteEndpoint == "" {
		return nil, ErrInvalidPTSiteEndpoint
	}

	if c.Timeout <= 0 {
		c.Timeout = defaultTimeout
	}

	if c.Interval <= 0 {
		c.Interval = defaultInterval
	}

	client := &http.Client{
		Timeout: c.Timeout,
	}

	return &hook{
		config: *c,
		client: client,
	}, nil
}

func NewDriver() middleware.Driver {
	return &driver{}
}

type driver struct{}

func (d *driver) NewHook(rawConfig []byte) (middleware.Hook, error) {
	var config Config
	err := yaml.Unmarshal(rawConfig, &config)
	if err != nil {
		return nil, err
	}

	return config.NewHook()
}
